<?php
namespace app\crm\model;
use think\Model;
use think\model\concern\SoftDelete;
use app\store\model\User;
use app\store\model\DictData;

class CrmContract extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    protected $globalScope = ['store_id'];
    public function scopeStore_id($query)
    {
        $query->where('store_id', StoreId())->where('customer_id','in', CrmCustomer::column('id'));
    }

    protected $type = [
        'datetime'     => 'timestamp:Y-m-d',
        'start_time'   => 'timestamp:Y-m-d',
        'end_time'     => 'timestamp:Y-m-d',
    ];

    /**
     * 关联部门表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    public function customer()
    {
        return $this->belongsTo(CrmCustomer::class, 'customer_id', 'id');
    }

    /**
     * 获取列表
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static function get_list() {
        return self::where('user_id','in', my_auth())->order('sort_order desc,id desc')->select();
    }
    //保存图片
    public function setPhotoAttr($value)
    {
        if(!$value){
            $list = array();
        }else{
            $list = implode(',',array_filter($value));
        }
        return $list;
    }
    //获取图片
    public function getPhotoAttr($value)
    {
        if(!$value){
            $list = array();
        }else{
            $list = explode(',', $value);
        }
        return $list;
    }

    /**
     * 快速读取关联产品
     * @param $value
     * @param $data
     * @return array
     */
    public function getGetProductAttr($value,$data)
    {
        $list = [];
        if(isset($data['product'])){
            $list = DictData::where('id','in',$data['product'])->column('name');
        }
        return $list;
    }

}